<!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="UTF-8">
	<title>定时器切换图片</title>
	<style>
		img {
			width: 200px;
			height: 200px;
			position: absolute;
			left: 50%;
			top: 50%;
			transform: translate(-50%, -50%);
		}

    #startBtn {
      width: 100px;
      height: 50px;
      position: absolute;
      left: 50%;
      transform: translateX(-60%);
    }

	</style>

	<script>



    window.onload = () => {
      let image = document.getElementById("box");
      // let imgPath = document.getElementById("imgPath");
      let imgArr = ["../images/demo06/bg1.jpg", "../images/demo06/bg2.jpg", "../images/demo06/bg3.jpg",
        "../images/demo06/bg4.jpg", "../images/demo06/bg5.jpg", "../images/demo06/bg6.jpg"];
      let num = 0;
      let startBtn = document.getElementById("startBtn");
      let stopBtn = document.getElementById("stopBtn");
      let timer;

      let start = () => {
        clearInterval(timer);   // 防止多次重复点击开始按钮, 每次开启定时器前首选移除上一次开启的定时器
        timer = setInterval(() => {
          num = num % imgArr.length;
          image.src = imgArr[num];
          num++;
        }, 100);
      };

      let flag = 1;
      startBtn.onclick = () => {
        if (flag % 2 === 1) {
          startBtn.innerHTML = "暂停";
          start();
        } else {
          clearInterval(timer);   // 清除定时器,
          startBtn.innerHTML = "开始";
        }
        flag++;
      };

    }

	</script>

</head>
<body>
<h1 id="imgPath"></h1>
<img id="box" src="../images/demo06/bg3.jpg">
<button id="startBtn">开始</button>
<!--<button id="stopBtn">停止</button>-->

</body>
</html>
